<?php
    include('IXR_Library.php');
    
    class SimpleServer extends IXR_Server {
        function SimpleServer() {
            $this->IXR_Server(array(
                'demo.checkLogin' => 'this:checkLogin',
                'demo.getExamsToId' => 'this:getExamsToId',
                'demo.examInformationToExamId' => 'this:examInformationToExamId',
                'demo.getExerciseType' => 'this:getExerciseType',
                'demo.getMaxPointsToExercise' => 'this:getMaxPointsToExercise',
                'demo.getMPChoiceExerciseId' => 'this:getMPChoiceExerciseId',
                'demo.getNbrAndIdOfMultipleChoiceQuestions' => 'this:getNbrAndIdOfMultipleChoiceQuestions',
                'demo.getSolutionIndexesToMPQuestion' => 'this:getSolutionIndexesToMPQuestion',
                'demo.getPointsPerSelection' => 'this:getPointsPerSelection',
                'demo.getEvaluationType' => 'this:getEvaluationType',
                'demo.workedExamsToExamId' => 'this:workedExamsToExamId',
                'demo.workedExamToExamIdWithMatrNrExists' => 'this:workedExamToExamIdWithMatrNrExists',
                'demo.insertWorkedExamAndExerciseResult' => 'this:insertWorkedExamAndExerciseResult',
                'demo.updateWorkedExamAndExerciseResult' => 'this:updateWorkedExamAndExerciseResult',
                'demo.getNumberOfParticipants' => 'this:getNumberOfParticipants',
                'demo.getNumberOfFailed' => 'this:getNumberOfFailed',
                'demo.getNumberOfPassed' => 'this:getNumberOfPassed',
                'demo.getAverageGrade' => 'this:getAverageGrade',
                'demo.getAverageGradeOfPassed' => 'this:getAverageGradeOfPassed',
                'demo.getAchievedPointsFirstCorrection' => 'this:getAchievedPointsFirstCorrection',
                'demo.getNumberOfExercises' => 'this:getNumberOfExercises',
                'demo.getGradingDistributionArray' => 'this:getGradingDistributionArray',
                'demo.getAveragePointsForExeciseInExam' => 'this:getAveragePointsForExeciseInExam',
                'demo.getGradeToAchievedPoints' => 'this:getGradeToAchievedPoints',
                'demo.getNumberOfExercisesFirstCorrected' => 'this:getNumberOfExercisesFirstCorrected',
                'demo.getNumberOfExercisesSecondCorrected' => 'this:getNumberOfExercisesSecondCorrected',
                'demo.getFirstCorrectedExercisesToWorkedExam' => 'this:getFirstCorrectedExercisesToWorkedExam',
                'demo.insertOrUpdateSecondCorrection' => 'this:insertOrUpdateSecondCorrection',
                'demo.updateGradeSecondCorrection' => 'this:updateGradeSecondCorrection'
            ));
        }
        
        /*
         * checking username and password provided by client; returning user id or -1
         */
        function checkLogin($args) {
            include 'dbconnect.php';
            
            $name = $args['user'];
            $password = $args['password'];
            
            $sql_query = "SELECT * FROM user_information WHERE accountname='$name'";
            
            $result = mysql_query($sql_query);     
            
            if(!$result || mysql_num_rows($result) == 0){
                return array('userId' => (int) -1);
            }
            
            $passwordInMYSQL = mysql_result($result, 0, "password");
            
            if(!$passwordInMYSQL){
                return array('userId' => (int) -1);
            }
            
            if(strcmp($passwordInMYSQL, $password) == 0){
                
                $userId = mysql_result($result, 0, "id");
                return array('userId' => (int) $userId);
                
            }

            return array('userId' => (int) -1);
        }
        
        /**
         * getting the exams of an user; 
         */
        function getExamsToId($userId) {
            include 'dbconnect.php';
                        
            $sql_query = "SELECT subjectId FROM exam_user_rel WHERE userId=$userId";
            
            $result = mysql_query($sql_query);
            
            
            if(!$result){
                return array("Id-0" => (int) -1);
            }
            
            if( mysql_num_rows($result) < 1){
                return array("Id-0" => (int) -2);
            }
            
            $examIds = array();
            
            for($i=0; $i<mysql_num_rows($result); $i++){
                $examIds["Id-".$i] = (int) mysql_result($result, $i, "subjectId");
            }
            return $examIds;
                      
        }
        
        /**
         *getting some information to an exam id
         * @param type $examId
         * @return type 
         */
        function examInformationToExamId($examId) {
            include 'dbconnect.php';
                        
            $sql_query = "SELECT * FROM exam WHERE id=$examId";
            
            $result = mysql_query($sql_query);
            
            
            if(!$result){
                return array("subjectId" => (String) "-1");
            }
            
            if( mysql_num_rows($result) < 1){
                return array("subjectId" => (String) "-2");
            }
            
            
            $examInformation = array();
            
            $examInformation["subjectId"] = (String) mysql_result($result, 0, "subjectId");
            $examInformation["subjectName"] = (String) mysql_result($result, 0, "subjectName");
            $examInformation["examDate"] = (String) mysql_result($result, 0, "examDate");
            $examInformation["evaluationBegin"] = (String) mysql_result($result, 0, "evaluationBegin");
            $examInformation["evaluationEnd"] = (String) mysql_result($result, 0, "evaluationEnd");
                        
            return $examInformation;
        }
        
        /**
         *get the exercise type of the exam id and the exercise number
         * @param type $args
         * @return type 
         */
        function getExerciseType($args) {
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            $exerciseId = $args['exerciseId'];
            
            $sql_query = "SELECT * FROM multipleChoiceExercise WHERE examId='$examId' AND exerciseNumber='$exerciseId'";
            
            $result = mysql_query($sql_query);     
            
            if(!$result){
                return array('exerciseType' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('exerciseType' => (int) 0);
            }
            
            $sql_query = "SELECT * FROM imageMultipleChoiceExercise WHERE examId='$examId' AND exerciseNumber='$exerciseId'";
            
            $result = mysql_query($sql_query);     
            
            if(!$result){
                return array('exerciseType' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('exerciseType' => (int) 1);
            }
            
            $sql_query = "SELECT * FROM freeTextExercise WHERE examId='$examId' AND exerciseNumber='$exerciseId'";
            
            $result = mysql_query($sql_query);     
            
            if(!$result){
                return array('exerciseType' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('exerciseType' => (int) 2);
            }
            

            return array('exerciseType' => (int) -1);
        }
        
        /**
         * maximal points of an exam id and exercise number
         * @param type $args
         * @return type 
         */
        function getMaxPointsToExercise($args) {
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            $exerciseId = $args['exerciseId'];
            
            $sql_query = "SELECT maxPointsInExercise FROM multipleChoiceExercise WHERE examId='$examId' AND exerciseNumber='$exerciseId'";
            
            $result = mysql_query($sql_query);     
            
            if(!$result){
                return array('maxPoints' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('maxPoints' => (int) mysql_result($result, 0, "maxPointsInExercise"));
            }
            
            $sql_query = "SELECT maxPointsInExercise FROM imageMultipleChoiceExercise WHERE examId='$examId' AND exerciseNumber='$exerciseId'";
            
            $result = mysql_query($sql_query);     
            
            if(!$result){
                return array('maxPoints' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('maxPoints' => (int) mysql_result($result, 0, "maxPointsInExercise"));
            }
            
            $sql_query = "SELECT maxPointsInExercise FROM freeTextExercise WHERE examId='$examId' AND exerciseNumber='$exerciseId'";
            
            $result = mysql_query($sql_query);     
            
            if(!$result){
                return array('maxPoints' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('maxPoints' => (int) mysql_result($result, 0, "maxPointsInExercise"));
            }
            return array('maxPoints' => (int) -1);
        }
            
        /**
         * exercise id of a (image) multiple choice question
         */
         function getMPChoiceExerciseId($args) {
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            $exerciseId = $args['exerciseId'];
            $exerciseType = $args['exerciseType'];
            
            if($exerciseType == 0){
                $sql_query = "SELECT id FROM multipleChoiceExercise WHERE examId='$examId' AND exerciseNumber='$exerciseId'";
            }else if($exerciseType == 1){
                $sql_query = "SELECT id FROM imageMultipleChoiceExercise WHERE examId='$examId' AND exerciseNumber='$exerciseId'";
            }
            $result = mysql_query($sql_query);     
            
            if(!$result){
                return array('exerciseId' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('exerciseId' => (int) mysql_result($result, 0, "id"));
            }
         }
         
        /**
         * number of questions and question ids of the question of an exercise to
         * the exercise id and the exercise type
         */
         function getNbrAndIdOfMultipleChoiceQuestions($args) {
            include 'dbconnect.php';
            
            $exerciseId = $args['exerciseId'];
            $exerciseType = $args['exerciseType'];
            
            if($exerciseType == 0){
                $sql_query = "SELECT count(*) FROM multipleChoiceQuestion WHERE exerciseId='$exerciseId'";
            }else if($exerciseType == 1){
                $sql_query = "SELECT count(*) FROM imageMultipleChoiceQuestion WHERE exerciseId='$exerciseId'";
            }
            
            $result = mysql_query($sql_query);     
            
            $mpChoiceIds = array();
            
            if(!$result){
                $mpChoiceIds["nbrOfMPChoiceQuestions"] = (int) -1;
                return $mpChoiceIds;
            }
            
            $count = (int) mysql_result($result, 0, "count(*)");
            
            $mpChoiceIds["nbrOfMPChoiceQuestions"] = (int) $count;
            
            if($exerciseType == 0){
                $sql_query = "SELECT id FROM multipleChoiceQuestion WHERE exerciseId='$exerciseId'";
            }else if($exerciseType == 1){
                $sql_query = "SELECT id FROM imageMultipleChoiceQuestion WHERE exerciseId='$exerciseId'";
            }
            
            $result = mysql_query($sql_query);
            
            for($i=0; $i<$count; $i++){
                $mpChoiceIds["Id-".$i] = (int) mysql_result($result, $i, "id");
            }
            return $mpChoiceIds;
            
         }
         
         /**
          *
          * number of correct solutions and indexes of the solutions
          * of a question id by using hte exercise type
          * 
          * @param type $args
          * @return type 
          */
         function getSolutionIndexesToMPQuestion($args) {
            include 'dbconnect.php';
            
            $questionId = $args['questionId'];
            $exerciseType = $args['exerciseType'];
                        
            if($exerciseType == 0){
                $sql_query = "SELECT count(*) FROM multipleChoiceQuestionAnswerPossibilities WHERE  multipleChoiceQuestionId=$questionId";
            }else if($exerciseType == 1){
                $sql_query = "SELECT count(*) FROM imageMultipleChoiceQuestionAnswerPossibilities WHERE  imageMultipleChoiceQuestionId=$questionId";
            }
            $result = mysql_query($sql_query);
            
            $mpChoiceSolution = array();
            
            if(!$result){
                $mpChoiceSolution["nbrOfAnswerPossibilites"] = (int) -1;
                return $mpChoiceSolution;
            }
            
            $count = (int) mysql_result($result, 0, "count(*)");
            
            $mpChoiceSolution["nbrOfAnswerPossibilites"] = (int) $count;
            
            if($exerciseType == 0){
                $sql_query = "SELECT count(*) FROM multipleChoiceQuestionSolutions WHERE  multipleChoiceQuestionId=$questionId";
            }else if($exerciseType == 1){
                $sql_query = "SELECT count(*) FROM imageMultipleChoiceQuestionSolutions WHERE  imageMultipleChoiceQuestionId=$questionId";
            }
            
            $result = mysql_query($sql_query);
            
            $count = (int) mysql_result($result, 0, "count(*)");
            
            $mpChoiceSolution["nbrOfCorrectAnswerPossibilites"] = (int) $count;
            
            if($exerciseType == 0){
                $sql_query = "SELECT indexOfBoxToMark FROM multipleChoiceQuestionSolutions WHERE multipleChoiceQuestionId='$questionId'";
            }else if($exerciseType == 1){
                $sql_query = "SELECT indexOfBoxToMark FROM imageMultipleChoiceQuestionSolutions WHERE imageMultipleChoiceQuestionId='$questionId'";
            }
            
            $result = mysql_query($sql_query);
            
            for($i=0; $i<$count; $i++){
                $mpChoiceSolution["Index-".$i] = (int) mysql_result($result, $i, "indexOfBoxToMark");
            }
            return $mpChoiceSolution;
        }
        
        /**
         *
         * points per selection value by exercise id using exercise type
         * 
         * @param type $args
         * @return type 
         */
        function getPointsPerSelection($args){
            include 'dbconnect.php';
            
            $exerciseId = (int) $args['exerciseId'];
            $exerciseType = (int) $args['exerciseType'];
            
            
            if($exerciseType == 0){
                $sql_query = "SELECT rightSelectionPoints FROM multipleChoiceExercise WHERE id=$exerciseId";
            }else if($exerciseType == 1){
                $sql_query = "SELECT rightSelectionPoints FROM imageMultipleChoiceExercise WHERE id=$exerciseId";
            }
            
            $result = mysql_query($sql_query);
            
            if(!$result){
                $pointsPerSelection['pointsPerSelection'] = (double) 0;
                return $pointsPerSelection;
            }
            
            $pointsPerSelection['pointsPerSelection'] = (double) mysql_result($result, 0, "rightSelectionPoints");
            return $pointsPerSelection;
            
        }
        
        /**
         *
         * evaluation type by exercise id using exercise type
         * 
         * @param type $args
         * @return type 
         */
        function getEvaluationType($args){
            include 'dbconnect.php';
            
            $exerciseId = (int) $args['exerciseId'];
            $exerciseType = (int) $args['exerciseType'];
            
            
            if($exerciseType == 0){
                $sql_query = "SELECT evaluationType FROM multipleChoiceExercise WHERE id=$exerciseId";
            }else if($exerciseType == 1){
                $sql_query = "SELECT evaluationType FROM imageMultipleChoiceExercise WHERE id=$exerciseId";
            }
            
            $result = mysql_query($sql_query);
            
            if(!$result){
                $evaluationType['evaluationType'] = (int) 0;
                return $evaluationType;
            }
            
            $evaluationType['evaluationType'] = (int) mysql_result($result, 0, "evaluationType");
            return $evaluationType;
            
        }
        
        /**
         * number of evaluated exams and their id to a exam id
         */
        function workedExamsToExamId($examId){
            include 'dbconnect.php';
            
            $sql_query = "SELECT count(*) FROM workedExam WHERE examId=$examId";
            $result = mysql_query($sql_query);
            
             $workedExams = array();
            
            if(!$result){
                $workedExams['size'] = (int) 0;
                return $workedExams;
            }
            
            $count = (int) mysql_result($result, 0, "count(*)");
            $workedExams['size'] = $count;
            
            $sql_query = "SELECT id FROM workedExam WHERE examId=$examId";
            $result = mysql_query($sql_query);
            
            for($i=0; $i<$count; $i++){
                $workedExams["Id-".$i] = (int) mysql_result($result, $i, "id");
            }
            
            return $workedExams;
        }
        
        /**
         * id of an worked exam to a exam id and a student
         * @param type $args
         * @return type 
         */
        function workedExamToExamIdWithMatrNrExists($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            $studentMatrNr = $args['studentsMatrNr'];
            
            $sql_query = "SELECT id FROM workedExam WHERE examId=$examId AND studentsMatrNr='$studentMatrNr'";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('workedExamId' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('workedExamId' => (int) mysql_result($result, 0, "id"));
            }
                
            return array('workedExamId' => (int) -1);
        }
        
        /**
         * insert given parameters into database.return id of inserted corrected exam.
        */ 
        function insertWorkedExamAndExerciseResult($args){
            include 'dbconnect.php';
            
            $examId = (int) $args['examId'];
            $studentMatrNr = (String) $args['studentsMatrNr'];  
            $studentsName = (String) $args['studentsName'];
            $correctionState = (int) $args['correctionState'];
            $exerciseNumber = (int) $args['exerciseNumber'];
            $archievedPoints = (double) $args['archievedPoints'];
             
            $sql_query = 
                "INSERT INTO workedExam (`examId`, `studentsName`, `studentsMatrNr`, `correctionState`) VALUES ($examId, '$studentsName', '$studentMatrNr', $correctionState)";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('workedExamId' => (int) -1);
            }
            
            $sql_query = "SELECT id FROM workedExam ORDER BY id DESC";
            $result = mysql_query($sql_query);
            if(!$result){
                return array('workedExamId' => (int) -1);
            }
            
            $workedExamId = (int) mysql_result($result, 0, "id");
            $sql_query = 
                "INSERT INTO workedExam_archievedPoints(`workedExamId`, `exerciseIndex`, `archievedPoints`) VALUES ($workedExamId, $exerciseNumber, $archievedPoints)";
            $result = mysql_query($sql_query);
            
            
            if(!$result){
                return array('workedExamId' => (int) -1);
            }
                
            return array('workedExamId' => $workedExamId);
        }
        
        /**
         *
         *  update given values, return whether correct
         * @param type $args
         * @return type 
         */
        function updateWorkedExamAndExerciseResult($args){
            include 'dbconnect.php';
            
            $workedExamId = (int) $args['workedExamId'];
            $examId = (int) $args['examId'];
            $studentMatrNr = (String) $args['studentsMatrNr'];
            $studentsName = (String) $args['studentsName'];
            $correctionState = (int) $args['correctionState'];
            $exerciseNumber = (int) $args['exerciseNumber'];
            $archievedPoints = (double) $args['archievedPoints'];
                         
            $sql_query = 
                "UPDATE workedExam SET `studentsName`='$studentsName', `correctionState`=$correctionState WHERE id=$workedExamId";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('correct' => (boolean) false);
            }
            
            $sql_query = 
                "SELECT * FROM workedExam_archievedPoints WHERE `workedExamId`=$workedExamId AND `exerciseIndex`=$exerciseNumber";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('correct' => (boolean) false);
            }
            
            if(mysql_num_rows($result)>0){
                $sql_query = 
                "UPDATE workedExam_archievedPoints SET `archievedPoints`=$archievedPoints WHERE `workedExamId`=$workedExamId AND `exerciseIndex`=$exerciseNumber";
            }else{
                $sql_query = 
                "INSERT INTO workedExam_archievedPoints(`workedExamId`, `exerciseIndex`, `archievedPoints`) VALUES ($workedExamId, $exerciseNumber, $archievedPoints)";
            }
            
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('correct' => (boolean) false);
            } 
            
            
            return array('correct' => (boolean) true);
        }
        
       
        /**
         * number of particpants using exam id
         * @param type $args
         * @return type 
         */
        function getNumberOfParticipants($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            
            $sql_query = "SELECT numberOfParticipants FROM exam WHERE id=$examId";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('nbrOfParticipants' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('nbrOfParticipants' => (int) mysql_result($result, 0, "numberOfParticipants"));
            }
        }
        
        /**
         * number of failed students by exam id
         * @param type $args
         * @return type 
         */
        function getNumberOfFailed($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            
            $sql_query = "SELECT count(*) FROM workedExam WHERE examId=$examId AND gradeDouble>4.0";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('nbrOfFailed' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('nbrOfFailed' => (int) mysql_result($result, 0, "count(*)"));
            }
        }
        
        /**
         *
         * @param type $args
         * @return type 
         */
        function getGradeToAchievedPoints($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            $workedExamId = $args['workedExamId'];
            $achievedPoints =$args['achievedPoints'];
            
            $sql_query = "SELECT MIN(grade) FROM exam_grading WHERE examId=$examId AND pointsNeeded<=$achievedPoints";
            $result = mysql_query($sql_query);
            
            $grade = (double) mysql_result($result, 0, "MIN(grade)");
            
            $sql_query = "UPDATE workedExam SET gradeDouble=$grade WHERE id=$workedExamId";
            $result = mysql_query($sql_query);
            
            return array('grade' => $grade);
            
        }
        
        /**
         * number of passed students by exam id
         * @param type $args
         * @return type 
         */
        function getNumberOfPassed($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            
            $sql_query = "SELECT count(*) FROM workedExam WHERE examId=$examId AND gradeDouble<=4.0";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('nbrOfPassed' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('nbrOfPassed' => (int) mysql_result($result, 0, "count(*)"));
            }
        }
        
        /**
         * average grad in exam
         * @param type $args
         * @return type 
         */
        function getAverageGrade($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            
            $sql_query = "SELECT AVG(gradeDouble) FROM workedExam WHERE examId=$examId";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('average' => (double) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('average' => (double) mysql_result($result, 0, "AVG(gradeDouble)"));
            }
        }
        /**
         * average grade of passed in exam
         * @param type $args
         * @return type 
         */
        function getAverageGradeOfPassed($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            
            $sql_query = "SELECT AVG(gradeDouble) FROM workedExam WHERE examId=$examId AND gradeDouble<=4.0";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('average' => (double) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('average' => (double) mysql_result($result, 0, "AVG(gradeDouble)"));
            }
        }
        
        /**
         *
         * achieved points of student in first correction
         * 
         * @param type $args
         * @return type 
         */
        function getAchievedPointsFirstCorrection($args){
            include 'dbconnect.php';
            
            $workedExamId = $args['workedExamId'];
                        
            $sql_query = "SELECT SUM(archievedPoints) FROM workedExam_archievedPoints WHERE workedExamId=$workedExamId";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('achievedPoints' => (double) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                return array('achievedPoints' => (double) mysql_result($result, 0, "SUM(archievedPoints)"));
            }
            
        }
        
        /**
         *
         * number of exercises of exam
         * 
         * @param type $args
         * @return type 
         */
        function getNumberOfExercises($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            
            $count = 0;
            
            $sql_query = "SELECT count(*) FROM multipleChoiceExercise WHERE examId=$examId";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('count' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                $count = $count + (int) mysql_result($result, 0, "count(*)");
            }
                        
            $sql_query = "SELECT count(*) FROM imageMultipleChoiceExercise WHERE examId=$examId";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('count' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                $count = $count + (int) mysql_result($result, 0, "count(*)");
            }
            
            $sql_query = "SELECT count(*) FROM freeTextExercise WHERE examId=$examId";
            $result = mysql_query($sql_query);
            
            if(!$result){
                return array('count' => (int) -1);
            }
            
            if(mysql_num_rows($result) > 0){
                $count = $count + (int) mysql_result($result, 0, "count(*)");
            }
            
           return array('count' => (int) $count);
        }
        
        /**
         *
         * grade distribution, which grade how often... of exam
         * 
         * @param type $args
         * @return type 
         */
        function getGradingDistributionArray($args){
            include 'dbconnect.php';
            
            $examId = $args['examId'];
            
            $gradeDistribution = array();
            
            $grades = array('1.0', '1.3', '1.7', '2.0', '2.3', '2.7', '3.0', '3.3', '3.7', '4.0', '4.3', '4.7', '5.0');
                        
            foreach ($grades as $value) {
    
                $sql_query = "SELECT count(*) FROM workedExam WHERE examId=$examId AND gradeDouble=$value";
                $result = mysql_query($sql_query);

                if(!$result){
                    $gradeDistribution[$value] = (int) 0;
                }

                if(mysql_num_rows($result) > 0){
                    $gradeDistribution[$value] = (int) mysql_result($result, 0, "count(*)");
                }
            }
            
            return $gradeDistribution;
            
            
        }
        
        /**
         *average points in an exercise in exam over all
         * @param type $args
         * @return type 
         */
        function getAveragePointsForExeciseInExam($args){
            include 'dbconnect.php';
                        
            $exerciseNumber = $args['exerciseNumber'];
            $nbrOfWorkedExams = $args['nbrOfWorkedExams'];
            $workedExamIds = array();
            
            $averagePoints = array();
            
            if($nbrOfWorkedExams>0){
                $OrClause = "";
                for($i=0; $i<$nbrOfWorkedExams; $i++){
                        $workedExamIds[$i] = $args["workedExamId$i"]; 
                    if($i==0){
                        $OrClause = "AND (workedExamId=$workedExamIds[$i]";
                    }else{
                        $OrClause = $OrClause . " OR workedExamId =$workedExamIds[$i]";
                    }
                }
                $OrClause = $OrClause . ")";
            }else{
                    $averagePoints["averagePoints"] = (double) 0;
                    return $averagePoints;
            }
            
               
            $sql_query = "SELECT AVG(archievedPoints) FROM workedExam_archievedPoints WHERE exerciseIndex=$exerciseNumber ".$OrClause;
            $result = mysql_query($sql_query);
            

                if(!$result){
                    $averagePoints["averagePoints"] = (double) 0;
                }

                if(mysql_num_rows($result) > 0){
                    $averagePoints["averagePoints"] = (double) mysql_result($result, 0, "AVG(archievedPoints)");
                }else{
                    $averagePoints["averagePoints"] = (double) 0;
                }
            
            return $averagePoints;
            
            
        }
        
        /**
         * nbr of first corrected exercises
         * 
         * @param type $args
         * @return type 
         */
        function getNumberOfExercisesFirstCorrected($args){
            include 'dbconnect.php';
                        
            $workedExamId = $args['workedExamId'];
            
            $sql_query = "SELECT COUNT(*) FROM workedExam_archievedPoints WHERE workedExamId=$workedExamId";
            $result = mysql_query($sql_query);
            
            return array("nbrOfExerciseFirstCorrected" =>  (int) mysql_result($result, 0, "COUNT(*)"));
            
        }
        
        /**
         * nbr of second corrected exercises
         * 
         * @param type $args
         * @return type 
         */
        function getNumberOfExercisesSecondCorrected($args){
            include 'dbconnect.php';
                        
            $workedExamId = $args['workedExamId'];
            
            $sql_query = "SELECT COUNT(*) FROM workedExam_archievedPoints_second WHERE workedExamId=$workedExamId";
            $result = mysql_query($sql_query);
            
            return array("nbrOfExerciseSecondCorrected" =>  (int) mysql_result($result, 0, "COUNT(*)"));
            
        }
        
        /**
         *
         * returns the indexes of the first corrected exercise in an evaluated exam
         * 
         * @param type $args
         * @return type 
         */
        function getFirstCorrectedExercisesToWorkedExam($args){
            include 'dbconnect.php';
            
            $workedExamId = $args['workedExamId'];
            
            $sql_query = "SELECT COUNT(*) FROM workedExam_archievedPoints WHERE workedExamId=$workedExamId";
            $result = mysql_query($sql_query);
            
            $count = (int) mysql_result($result, 0, "COUNT(*)");
            
            $sql_query = "SELECT exerciseIndex FROM workedExam_archievedPoints WHERE workedExamId=$workedExamId";
            $result = mysql_query($sql_query);
            
            $correctedExercises = array();
             
            $correctedExercises['size'] = (int) $count;
                        
            for($i=0; $i<$count; $i++){
                $correctedExercises["Counter-".$i] = (int) mysql_result($result, $i, "exerciseIndex");            
            }
            
            return $correctedExercises;
        }
        
        /**
         *
         * inserts/updates the second correction an exercise
         * 
         * @param type $args
         * @return type 
         */
        function insertOrUpdateSecondCorrection($args){
            include 'dbconnect.php';
            $workedExamId = (int) $args['workedExamId'];
            $exerciseNumber = (int) $args['exerciseNumber'];
            $achievedPoints = (double) $args['achievedPoints'];
            
            
            $sql_query = "SELECT COUNT(*) FROM workedExam_archievedPoints_second WHERE workedExamId='$workedExamId' AND exerciseIndex='$exerciseNumber'";
                        
                
            $result = mysql_query($sql_query);
            
            $count = (int) mysql_result($result, 0, "COUNT(*)");
                        
            if($count>0){
                $sql_query = "UPDATE workedExam_archievedPoints_second SET achievedPoints=$achievedPoints WHERE workedExamId=$workedExamId AND exerciseIndex=$exerciseNumber";
            }else{
                $sql_query = "INSERT INTO workedExam_archievedPoints_second(workedExamId, exerciseIndex, achievedPoints) VALUES ($workedExamId, $exerciseNumber, $achievedPoints)";
             
            }
            
            $correct = (bool) mysql_query($sql_query);
            
            return array('result' => $correct);
        }
        
        /**
         *
         * update the grade after adding a second correctio
         * 
         * @param type $args
         * @return type 
         */
        function updateGradeSecondCorrection($args){
            include 'dbconnect.php';
            $examId = (int) $args['examId'];
            $workedExamId = (int) $args['workedExamId'];
                        
            $sql_query = "SELECT SUM(achievedPoints) FROM workedExam_archievedPoints_second WHERE workedExamId='$workedExamId'";
                                        
            $result = mysql_query($sql_query);
            
            $sum = (double) mysql_result($result, 0, "SUM(achievedPoints)");
                        
            $sql_query = "SELECT COUNT(grade) FROM exam_grading WHERE pointsNeeded<=$sum AND examId=$examId"; 
            
            $result = mysql_query($sql_query);
            
            $grade_number = (double) mysql_result($result, 0, "COUNT(grade)");
            
            if($grade_number < 1){
                $sql_query = "UPDATE workedExam SET gradeSecondDouble=5.0 WHERE id=$workedExamId";
            
                $correct = (bool) mysql_query($sql_query);

                return array('result' => (double)5.0);
            }
                        
            $sql_query = "SELECT MIN(grade) FROM exam_grading WHERE pointsNeeded<='$sum' AND examId='$examId'"; 
            
            $result_new = mysql_query($sql_query);
            
            $grade = (double) mysql_result($result_new, 0, "MIN(grade)");
            
            $sql_query = "UPDATE workedExam SET gradeSecondDouble='$grade' WHERE id='$workedExamId'";
                
            $correct = (bool) mysql_query($sql_query);
                        
            return array('result' => (double) $grade);
        }
        
        
    }
            

    $server = new SimpleServer();   
?>